/* 点位资讯设定 */
import React, { useState, useEffect } from 'react';
import { withRouter } from 'umi';
import Request from 'umi-request';
import {
  Row,
  Col,
  Form,
  Table,
  Input,
  Typography,
  Popconfirm,
  Select,
  Switch,
  Button,
  Upload,
  Space,
  Popover,
  notification,
} from 'antd';
import {
  listAllByDeviceTypeAndID,
  tagMapAdd,
  tagMapUpdate,
  tagMapImport,
} from './setServers';
import styles from '@/assets/setting/BuildSet.less';

const { TextArea } = Input;
const { Option } = Select;

const selectList = [
  'NA',
  'integer',
  'float',
  'boolean',
  'word',
  'dword',
  'double',
];

function TagMapping(props: any) {
  const { history, location, match } = props;
  // console.log(history, location, match);
  if (!location['state']) {
    history.push('/sensorSet');
  }

  const [FormEditTab] = Form.useForm();
  type TableData = { [key: string]: any }[];
  const [importExcel, setImportExcel] = useState(false);
  const [tableDatas, settableDatas] = useState<TableData>([]);
  // 判断 是 新增还是更新，同时添加之前的信息
  const [judgeAddUp, setJudgeAddUp] = useState({
    NOWTYPE: 'ADD',
    __seqid: '',
    ITEMID: '',
  });
  // 判读是否展开编辑
  const [editingKey, setEditingKey] = useState('');

  //
  const isEditing = (record: any) => record.key === editingKey;
  // 编辑同时向form表单中插入数据
  const editForm = (record: any) => {
    FormEditTab.setFieldsValue({
      ITEMNAME: '',
      NODEID: '',
      KEPITEMID: '',
      TAGNAME: '',
      ADDRESS: '',
      VALUETYPE: '',
      AUTOCONTROL: '',
      // SEQID: '',
      ...record,
    });
    setEditingKey(record.key);
  };
  // 编辑取消
  const cancel = () => {
    setEditingKey('');
  };
  // 获取数据
  const getTableData = () => {
    listAllByDeviceTypeAndID(match['params']).then((res) => {
      // console.log('获取跳转的值', res);
      const originData: TableData[] = [];
      res['data'] &&
        res['data'].forEach((item: any, i: number) => {
          originData.push({
            key: i.toString(16),
            ...item,
          });
        });
      settableDatas(originData);
    });
  };
  // 编辑并保存数据
  const save = async (key: any) => {
    try {
      const row = await FormEditTab.validateFields();
      const newData = [...tableDatas];
      const index = newData.findIndex((item: any) => key === item.key);
      console.log('row', row, key, index, '状态！！', judgeAddUp);
      const upParams = {
        devicetype: match['params']['deviceType'],
        id: match['params']['id'],
        itemid: judgeAddUp['ITEMID'],

        seqid: judgeAddUp['__seqid'],
        itemname: row['ITEMNAME'],
        nodeid: row['NODEID'],
        kepitemid: row['KEPITEMID'],
        tagname: row['TAGNAME'],
        address: row['ADDRESS'],
        valuetype: row['VALUETYPE'],
        autocontrol: row['AUTOCONTROL'] ? 'Y' : 'N',
      };
      if (judgeAddUp.NOWTYPE === 'UP') {
        // 编辑,更新
        tagMapUpdate(upParams).then((res) => {
          console.log('点位资讯设定 res 编辑 是否成功', res);
          if (res.code >= 0) {
            getTableData();
            setEditingKey('');
            notification.success({
              message: '修改结果！',
              description: res.message || '修改成功！',
            });
          } else {
            notification.error({
              message: '修改结果！',
              description: res.message || '修改失败！',
            });
          }
        });
      } else if (judgeAddUp.NOWTYPE === 'ADD') {
        // 添加
        tagMapAdd(upParams).then((res) => {
          // console.log('点位资讯设定 res 添加 是否成功', res);
          if (res.code >= 0) {
            getTableData();
            setEditingKey('');
            notification.success({
              message: '添加结果！',
              description: res.message || '添加成功！',
            });
          } else {
            notification.error({
              message: '添加结果！',
              description: res.message || '添加失败！',
            });
          }
        });
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  useEffect(() => {
    getTableData();
  }, []);

  // 表头
  const columns = [
    {
      title: '感测项目',
      dataIndex: 'ITEMNAME',
      key: 'ITEMNAME',
      editable: true,
    },
    { title: 'Node ID', dataIndex: 'NODEID', key: 'NODEID', editable: true },
    {
      title: 'Item ID(KEP)',
      dataIndex: 'KEPITEMID',
      key: 'KEPITEMID',
      editable: true,
    },
    {
      title: 'Tag Name(KEP)',
      dataIndex: 'TAGNAME',
      key: 'TAGNAME',
      editable: true,
    },
    {
      title: 'Address(KEP)',
      dataIndex: 'ADDRESS',
      key: 'ADDRESS',
      editable: true,
    },
    {
      title: '资料形态',
      dataIndex: 'VALUETYPE',
      key: 'VALUETYPE',
      editable: true,
    },
    {
      title: '可控制',
      dataIndex: 'AUTOCONTROL',
      key: 'AUTOCONTROL',
      editable: true,
    },
    {
      title: '编辑',
      dataIndex: 'edit',
      render: (_: string, record: any) => {
        const editable = isEditing(record);
        // console.log( record.key, record, editable );
        return editable ? (
          <span>
            <Button
              type="link"
              onClick={() => {
                // console.log('record key', record, record.key);
                save(record['key']);
              }}
            >
              修改
            </Button>
            <Popconfirm title="确定取消?" onConfirm={cancel}>
              <Button type="link">取消</Button>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link
            disabled={editingKey !== ''}
            onClick={() => {
              if (record['AUTOCONTROL']) {
                setJudgeAddUp({
                  NOWTYPE: 'UP',
                  __seqid: record['SEQID'],
                  ...record,
                });
              } else {
                setJudgeAddUp({
                  NOWTYPE: 'ADD',
                  __seqid: record['SEQID'],
                  ...record,
                });
              }
              console.log(
                record,
                record['AUTOCONTROL'],
                '状态！！',
                judgeAddUp,
              );
              editForm(record);
            }}
          >
            编辑
          </Typography.Link>
        );
      },
    },
  ];
  // 给表头添加部分信息
  const mergedColumns = columns.map((col: any) => {
    // console.log('col ???????', col);
    if (!col.editable) return col;
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        // editType: col['dataIndex'] === 'VALUETYPE'
        dataIndex: col['dataIndex'],
        title: col['title'],
        editing: isEditing(record),
      }),
    };
  });

  // 表格行点击后的编辑
  const EditableCell = (tdData: any) => {
    const { children } = tdData;
    const { editing, dataIndex, record } = tdData;

    // console.log('tdData ????????????///', tdData);
    // 判断不同场景
    const rDefaultDom = () => {
      if (dataIndex === 'ITEMNAME') {
        return (
          <Form.Item name={dataIndex}>
            <Input disabled />
          </Form.Item>
        );
      } else if (dataIndex === 'VALUETYPE') {
        return (
          <Form.Item name={dataIndex}>
            <Select style={{ width: 80 }}>
              {selectList.map((item: string) => (
                <Option key={item} value={item}>
                  {item}
                </Option>
              ))}
            </Select>
          </Form.Item>
        );
      } else if (dataIndex === 'AUTOCONTROL') {
        return (
          <Form.Item
            name={dataIndex}
            valuePropName={
              record['AUTOCONTROL'] === 'Y'
                ? 'defaultChecked'
                : 'unCheckedChildren'
            }
          >
            <Switch checkedChildren="Y" unCheckedChildren="N" />
            {/* <Checkbox 
              onChange={(e)=>{
                console.log(e, 'change 事件改变！！！', e.target.checked);
                if( e.target.checked ){

                }
              }}
            ></Checkbox> */}
          </Form.Item>
        );
      } else {
        return (
          <Form.Item name={dataIndex}>
            <TextArea />
          </Form.Item>
        );
      }
    };
    return <td>{editing ? rDefaultDom() : children}</td>;
  };

  // // 上传
  // const upLoadProps = {
  //   name: "file",
  //   action: "http://172.28.146.72:9100/sh_energy/device/ice_maker_tag_mapping/import",
  //   showUploadList: false,
  //   headers: {
  //     // "authorization": JSON.parse(sessionStorage.getItem('userData'))['token'],
  //   },
  //   onchange(info: any) {

  //     console.log('上传文件 info', info);
  //   }
  // }
  const upExcelFile = () => {
    setImportExcel(true);
    let MYINPUT = document.createElement('input');
    MYINPUT.name = 'up__Files';
    MYINPUT.type = 'file';
    MYINPUT.onclick = function (e: any) {
      e.target.value = '';
    };
    MYINPUT.click();
    MYINPUT.onchange = function (e: any) {
      let formData = new FormData();
      formData.append('file', e.currentTarget.files[0]);
      // console.log('input 中的', e, e.currentTarget.files[0], formData)

      tagMapImport(formData)
        .then((res) => {
          // console.log('文件是否上传成功', res);
          if (res.code >= 0) {
            notification.success({
              message: '数据批量上传结果！',
              description: res.message || '数据批量上传成功！',
            });
            getTableData();
          } else {
            notification.error({
              message: '数据批量上传结果！',
              description: res.message || '数据批量上传失败！',
            });
          }
        })
        .finally(() => {
          setImportExcel(false);
        });
    };
  };

  return (
    <div>
      <h2>点位资讯设定</h2>
      <Row gutter={24}>
        <Col span={20} style={{}}>
          <span>
            {'感测器名称：'}
            {location['state'] ? location['state']['AREANAME'] : ''}
          </span>
        </Col>
        <Col span={4}>
          <Space>
            <Popover
              title="请选择类型！"
              trigger="hover"
              content={
                <Space>
                  <Button
                    onClick={() => {
                      window.open('/energy/iceMachineSystem/冰机导入模板.xls');
                    }}
                  >
                    下载模板
                  </Button>
                  {/* <Upload {...upLoadProps}>
                  <Button type="primary">上传文件</Button>
                </Upload> */}
                  <Button type="primary" onClick={upExcelFile}>
                    上传文件
                  </Button>
                </Space>
              }
            >
              <Button danger loading={importExcel}>
                {'批量导入'}
              </Button>
            </Popover>
            <Button
              type="primary"
              ghost
              onClick={() => {
                // history.go(-1);
                history.push('/sensorSet');
              }}
            >
              {'返回 感测器资讯设定'}
            </Button>
          </Space>
        </Col>
      </Row>

      {/* 在表格中编辑数据 */}
      <Form form={FormEditTab} component={false}>
        <Table
          components={{
            // 自定义
            body: {
              cell: EditableCell,
            },
          }}
          size="small"
          bordered
          dataSource={tableDatas}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={false}
          // pagination={{
          //   // onChange: cancel,
          // }}
          className={styles['sensorSetTab']}
        />
      </Form>
    </div>
  );
}

export default withRouter(TagMapping);
